<?php

namespace app\common\driver;

use think\log\driver\File;

class LogHandler extends File
{
    /**
     * 日志写入接口
     * @access public
     * @param array $log 日志信息
     * @return bool
     */
    public function save(array $log): bool
    {
        $destination = $this->getMasterLogFile();
        
        $path = dirname($destination);
        // 需要注意命令行调用的话是没有请求的
        if (function_exists('request')) {
            $request = request();
            // 获取模块名，也就是请求路径的第一个元素
            $pathinfo = $request->pathinfo();
            $paths = explode('/', $pathinfo);
            $modulePath = isset($paths[0]) ? (strtolower($paths[0]). DIRECTORY_SEPARATOR) : '';
            // 把log 替换成log/模块名
            $path = preg_replace('/\/log\//', '/log/' . $modulePath, $path);
            $destination = preg_replace('/\/log\//', '/log/' . $modulePath, $destination);
        }
        !is_dir($path) && mkdir($path, 0755, true);

        $info = [];

        // 日志信息封装
        $time = \DateTime::createFromFormat('0.u00 U', microtime())->setTimezone(new \DateTimeZone(date_default_timezone_get()))->format($this->config['time_format']);

        foreach ($log as $type => $val) {
            $message = [];
            // 把日志类型转换成大写，我也不知道为什么tp默认是小写，全世界都大写就它小写
            $type = strtoupper($type);
            foreach ($val as $msg) {
                if (!is_string($msg)) {
                    $msg = var_export($msg, true);
                }

                $message[] = $this->config['json'] ?
                json_encode(['time' => $time, 'type' => $type, 'msg' => $msg], $this->config['json_options']) :
                sprintf($this->config['format'], $time, $type, $msg);
            }

            if (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level'])) {
                // 独立记录的日志级别
                $filename = $this->getApartLevelFile($path, $type);
                $this->write($message, $filename);
                continue;
            }

            $info[$type] = $message;
        }

        if ($info) {
            return $this->write($info, $destination);
        }

        return true;
    }
}